#!/bin/bash

SERVICE_PATH="/opt/middleware/AtlasEdge/software/edge_site/edge_manager/config"
SCRIPT_PATH="/opt/middleware/AtlasEdge/software/edge_site/edge_manager/src/script"
WORK_PATH="/opt/middleware/AtlasEdge"

. ${SCRIPT_PATH}/common.sh
. ${SCRIPT_PATH}/log_util.sh

ATLASEDGE_SERVICE_FILE="atlasedge.service"
ATLASEDGE_CONFIG_FILE="${WORK_PATH}/config/config.ini"

function usage() {
    echo "start -- start and demo software"
    echo "parameters:"
    echo "usage: "
    echo "     start"
}

precheck_env() {
    return 0
}

start_edge()
{
    NO_SYS_LOAD_MODE=`ReadINIfile ${ATLASEDGE_CONFIG_FILE} SYS no_sys_load_mode`
    if [ "${NO_SYS_LOAD_MODE}" == "1" ]; then
        logger_Info "atlasEdge is no_sys_load_mode no need start"
        return 0
    fi

    # check service is enable
    local strIsEnable=`sudo systemctl is-enabled ${ATLASEDGE_SERVICE_FILE} 2>/dev/null`
    local strIsActive=`sudo systemctl is-active ${ATLASEDGE_SERVICE_FILE} 2>/dev/null`
    if [ "${strIsEnable}" == "enabled" -a "$strIsActive" == "active" ]; then
        runInfo=`sudo systemctl show -p ExecStart atlasedge.service --no-pager`
        logger_Info "atlasEdge is running already "
        return 0
    fi

    start_service ${SERVICE_PATH} ${ATLASEDGE_SERVICE_FILE}
    local start_rt=$?
    if [ ${start_rt} -eq 0 ]; then
        LOG_PATH=`ReadINIfile ${ATLASEDGE_CONFIG_FILE} SYS log_path`
        logger_Info "atlasEdge server is start now. "
        logger_Info "please check log $(basename ${LOG_PATH})/atlasedge_script.log or call 'systemctl status atlasedge' check progress status"
    else
        logger_Warn "atlasEdge server is not start please check log $(basename ${LOG_PATH})/atlasedge_script.log"
    fi
}

restart_atlasedge()
{
    NO_SYS_LOAD_MODE=`ReadINIfile ${ATLASEDGE_CONFIG_FILE} SYS no_sys_load_mode`
    if [ "${NO_SYS_LOAD_MODE}" == "1" ]; then
        logger_Info "atlasEdge restart in no_sys_load_mode just stop"
        bash ${SCRIPT_PATH}/stop.sh
        return 0
    else
        logger_Info "atlasEdge restart system restart"
        sudo rm -f /lib/systemd/system/${ATLASEDGE_SERVICE_FILE}
        sudo cp -f ${SERVICE_PATH}/${ATLASEDGE_SERVICE_FILE} /lib/systemd/system
        sudo systemctl daemon-reload
        sudo systemctl restart atlasedge
    fi
}

main()
{
    if [ "$#" -gt 0 ]; then
        if [ "$1" == "-h" ]; then
            usage
            return 0
        elif [ "$1" == "restart" ]; then
            restart_atlasedge
            return 0
        fi
    fi

    precheck_env
    start_edge
}

main "$@"
RESULT=$?
exit $RESULT